<template>
    <div>
        <dialog-alert :data="alertData" @on-close="onCloseAlert()" @on-confirm="submitForm(ruleFormRef)">
            <div class="dialog-alert">
                <el-form ref="ruleFormRef" :model="addToPoemsListData" :rules="rules" label-width="120px" class="demo-ruleForm" 
                    :size="formSize" :status-icon="false">
                    <el-form-item label="选择诗单：" prop="pl_name" class="author">
                        <el-select v-model="addToPoemsListData.pl_name" filterable remote reserve-keyword @change="choosePoemsList"
                            placeholder="请填写诗单名称" :remote-method="SearchPoemsListByName" :loading="loading" > 
                            <el-option v-for="item in poemsList" :key="item.pl_id" :label="item.pl_name" :value="item.pl_id" />
                        </el-select>
                    </el-form-item>
                    <div>没有符合的诗单？<a @click="createPoemsList()">点击创建新的诗单</a></div>
                </el-form>
            </div>
        </dialog-alert>
    </div>
    <create-alert :type="'create'" v-if="isShowCreatePoemsListAlert" @closeCreatePoemsListlAlert="closeCreatePoemsListlAlert"></create-alert>
</template>

<script setup lang="ts">
import { clearObject } from '@/utils/util'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { reactive, ref, toRefs } from 'vue'
import managePoemsListStore from '../../../manage-poemsList/manage-poemsList.store'
import CreateAlert from './create-poems-list.vue'

const managePoemsListSe = managePoemsListStore()
const props = defineProps({
    pid: {
        type: Number,
        default: -1
    }
})
const { pid } = toRefs(props)

let addToPoemsListData = reactive({
    pl_id: -1,
    pl_name: ''
})

// 表单校验
const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
// 校验规则
const rules = reactive<FormRules>({
    pl_name: [{ 
        required: true, 
        message: '请选择诗单', 
        trigger: ['change', 'blur'] 
    }]
})
// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            onConfirm()
        }
    })
}
// 清空表单
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    Object.assign(addToPoemsListData, clearObject(addToPoemsListData))
}

let poemsList = ref<any>([])
let loading = ref<boolean>(false)
let timer = ref<any>(null)
// 根据名称搜索诗单
const SearchPoemsListByName = (query: string) => {
    if(query == '') {
        poemsList.value = []
        return 
    }
    loading.value = true
    if(timer.value) clearTimeout(timer.value) 
    timer.value = setTimeout(() => {
        const data = {
            pl_name: query
        }
        managePoemsListSe.getSearchPoemsListByNameAndUid(data).then((res: any) => {
            loading.value = false
            if(res.status == 'success') {
                poemsList.value = res.results
            } else {
                ElMessage({
                    showClose: true,
                    message: '获取诗单数据失败！',
                    type: 'error',
                })
            }
        })
    }, 300)
}
// 选中诗单时
const choosePoemsList = (value: number) => {
    addToPoemsListData.pl_id = value
}

const emits = defineEmits(['closeAddToPomesListAlert'])
// 添加诗歌至诗单信息
const alertData = {
    title: '添加诗歌至诗单信息',
    confirmTitle: '添加',
    isShowCancleBtn: true,
    cancleTitle: '取消',
    isShowClose: true,
}
// 点击取消/关闭
const onCloseAlert = () => {
    emits('closeAddToPomesListAlert', false)
}
// 点击添加
const onConfirm = () => {
    const data = {
        pid: pid.value,
        pl_id: addToPoemsListData.pl_id
    }
    managePoemsListSe.getAddPoetryToPoemsList(data).then((res: any) => {
        if(res.status == 'success') {
            emits('closeAddToPomesListAlert', true)
        } else if(res.errCode && res.errCode != '') {
            ElMessage({
                showClose: true,
                message: res.errMessage,
                type: 'error',
            })
        }else {
            ElMessage({
                showClose: true,
                message: '加入诗单失败！',
                type: 'error',
            })
            addToPoemsListData.pl_id = -1
            addToPoemsListData.pl_name = ''
        }
    })
}

// 创建新的诗单
let isShowCreatePoemsListAlert = ref<boolean>(false)
// 打开创建诗单弹窗
const createPoemsList = () => {
    isShowCreatePoemsListAlert.value = true
}
// 关闭创建诗单弹窗
const closeCreatePoemsListlAlert = () => {
    isShowCreatePoemsListAlert.value = false
}
</script>

<style lang="less" scoped>
a {
    color: var(--pc-a-color);
    cursor: pointer;
    text-decoration: underline;
}
</style>